<script setup>
import {nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";
import AdminCreate from './admin-create.vue';
import AdminAppend from './admin-append.vue';
import _ from 'lodash';
import TreeItemName from '../role/tree-item-name.vue';
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";

const {
  showCreate,
  modId,
  isView,
  winName,
  list,
  loading,
  pagination,
  datasTableHeight,
  userMenuTitle,
  userMenuShow,
  userMenus,
  userLoading,
  qrcodeUser,
  qrcodeWinName,
  qrcodeShow,
  qrcodeBindUrl,
  treeSetting,
  showAppend,
  pwdShow,
  pwdForm,
  pwdUser,
  pwdTip,
  rules
} = toRefs(reactive({
  showCreate: false,
  modId: null,
  isView: false,
  winName: '新增',
  list: [],
  loading: false,
  pagination: {
    current: 1,
    pageSize: 50,
    total: 0
  },
  datasTableHeight: 500,

  // menuUser: {},
  userMenuTitle: '',
  userMenuShow: false,
  userMenus: [],
  userLoading: false,

  qrcodeUser: null,
  qrcodeWinName: "",
  qrcodeShow: false,
  qrcodeBindUrl: "",

  treeSetting: {children: 'subs', label: 'name'},

  showAppend: false,

  pwdShow: false,
  pwdForm: {
    pwd1: "",
    pwd2: ""
  },
  pwdUser: null,
  pwdTip: "",
  rules: {
    pwd1: [
      {required: true, message: '请输入密码', trigger: 'blur'}
    ],
    pwd2: [
      {required: true, message: '请再次确认密码', trigger: 'blur'}
    ]
  }
}))

const datasContainerRef = ref(null)
const selectedtreeRef = ref(null);
const selectedtreeT2Ref = ref(null);
const selectedtreeT3Ref = ref(null);
const selectedtreeT9Ref = ref(null);
const pwdFormRef = ref(null)

watch(() => qrcodeShow.value, (val) => {
  if (val === false) {
    refresh();
  }
})

onMounted(() => {
  init();
  refresh();
})

const adminTypeLabel = (type) => {
  if (type === 'MGR') {
    return '管理员';
  } else if (type === 'SUPER') {
    return '管理员';
  } else if (type === '_SUPER') {
    return '系统管理员';
  } else {
    return '管理员';
  }
}

const init = () => {
  /*nextTick(() => {
    handleResize();
  });*/
}

/*const handleResize = () => {
  if (!datasContainerRef.value?.getBoundingClientRect) return;

  let rect = datasContainerRef.value.getBoundingClientRect();
  let height = _.get(rect, 'height');

  if (searchMode.value) {
    datasTableHeight.value = 300;
  } else {
    if (height > 0) {
      datasTableHeight.value = height;
    }
  }
}*/

const canMod = (admin) => {
  return true;
}

const refresh = async () => {

  loading.value = true;
  let data = await api.adminmgr.getList({
    page: pagination.value.current,
    pageSize: pagination.value.pageSize
  });

  loading.value = false;
  if (data) {
    pagination.value.total = data.count;
    list.value = data.rows || [];
  }
}

const closeWin = (flag) => {
  showCreate.value = false;
  showAppend.value = false;
  if (flag) {
    refresh();
  }
}

const showCreateWin = () => {
  showCreate.value = true;
  modId.value = null;
  isView.value = false;
  winName.value = '新增内容';
}

const showSelectUserWin = () => {
  showAppend.value = true;
}

const handleView = (it) => {
  modId.value = it.id;
  showCreate.value = true;
  isView.value = true;
}

const handleEdit = (it) => {
  modId.value = it.id;
  showCreate.value = true;
  isView.value = false;
}

const _removeAdmin = async (id) => {
  if (!id) return;

  let ret = await api.adminmgr.removeMgr(id);
  if (ret) refresh();
}

const handleRemoveAdmin = (it) => {
  if (!it || !it.id) {
    return;
  }
  $jui.confirm(`此操作将清除用户【${it.nickname}】所有权限（用户仍然会显示在普通人员管理中）, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    _removeAdmin(it.id);
  }).catch(() => {

  });
}

const _delete = async (id) => {
  let ret = await api.adminmgr.disable(id);
  if (ret) {
    $jui.toast("删除成功！");
    refresh();
  }
}

const handleDelete = (it) => {
  if (!it || !it.id) {
    return;
  }
  $jui.confirm(`删除用户将不可恢复，请谨慎操作，确定删除该用户?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    _delete(it.id);
  }).catch(() => {

  });
}

const handleShowMenu = async (user) => {
  let uid = _.get(user, 'id');

  if (!user || !uid) return;

  userMenuShow.value = true;
  userMenuTitle.value = `用户【${_.get(user, 'nickname')}】的菜单树`;
  userLoading.value = true;

  let menus = await api.admin.getAdminSubMenusTree(-1, null, {admin_id: uid});

  userMenus.value = menus;
  // menuUser = user;
  userLoading.value = false;

  await nextTick(() => {
    selectedtreeRef.value?.filter();
    selectedtreeT2Ref.value?.filter();
    selectedtreeT3Ref.value?.filter();
    selectedtreeT9Ref.value?.filter();
  });
}

const isBindWxsp = (admin) => {
  let accounts = _.get(admin, 'customer.accounts');

  return admin.isBindWxsp || _.findIndex(accounts, {type: 3}) >= 0;
}

const handleShowUnbind = async (admin) => {
  let id = _.get(admin, 'id');
  let name = _.get(admin, "nickname") || _.get(admin, "loginname");

  $jui.confirm(`确认解绑当前账号【${name}】?`, "警告").then(async () => {
    let ret = await api.adminmgr.unbindWxsp(id);

    if (ret) {
      refresh();
    }
  }).catch(e => {
  });
}

const handleShowQrcode = (user) => {
  let account = _.get(user, 'loginname');

  if (!account) return;

  qrcodeUser.value = user;
  qrcodeBindUrl.value = `${window.location.origin}/api/web/common/wxBindUrl?account=${account}`;
  qrcodeShow.value = true;
  qrcodeWinName.value = `绑定账号 ${account}`;
}

const handleMenuFilter = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 1;
}

const handleMenuFilterT2 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 2;
}

const handleMenuFilterT3 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 3;
}

const handleMenuFilterT9 = (value, data, node) => {
  let tty = _.get(data, 'tty');
  return tty === 9;
}

const handleShowChangePwd = (u) => {
  pwdUser.value = u;
  pwdShow.value = true;
  pwdFormRef.value.resetFields();

  let name = _.get(u, "nickname");
  let code = _.get(u, "loginname");

  let tip = name;
  if (!name) {
    tip = code;
  } else {
    tip = `${name}/${code}`;
  }
  pwdTip.value = tip;
}

const handleChangePwd = async () => {
  let pwd1 = _.trim(pwdForm.value.pwd1);
  let pwd2 = _.trim(pwdForm.value.pwd2);
  let uid = _.get(pwdUser.value, "id");

  if (!uid) {
    $jui.toast("修改用户不明确！");
    return;
  }

  if (!pwd1 || !pwd2) {
    $jui.toast("密码不能为空");
    return;
  }

  if (pwd1 !== pwd2) {
    $jui.toast("两次密码不一致");
    return;
  }

  let ret = await api.adminmgr.changePwd(uid, pwd1);

  if (ret) {
    $jui.toast("修改成功！");
    handlePwdClose();
  }
}

const handlePwdClose = () => {
  pwdShow.value = false;
}
</script>
<template>
  <div class="jzlpage-container datas-container" v-loading="loading">
    <!--<h3 class="page-title"> 管理员管理 <small></small></h3>-->
    <div class="datas-search">
      <el-button
        size="mini"
        type="primary"
        @click="showCreateWin()"
      >
        <template #icon>
          <JIcon :icon="DFT_ICONS.add"></JIcon>
        </template>管理员
      </el-button>
      <el-button
        size="mini"
        type="primary"
        @click="showSelectUserWin()"
      >
        <template #icon>
          <JIcon :icon="DFT_ICONS.sync" />
        </template>用户批量设置为管理员
      </el-button>
    </div>
    <div
      class="m-table-container"
      ref="datasContainerRef">
      <el-table
        :data="list"
        border
        size="small"
        class="w-full m-table"
      >
        <el-table-column
          prop="loginname"
          label="登录名"
          width="260">
          <template #default="scope">
            {{ scope.row.loginname }}
          </template>
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="昵称"
          width="260"
        ></el-table-column>
        <!--<el-table-column prop="type" label="类型">
            <template slot-scope="scope">
                {{ scope.row.type | adminTypeLabel }}
            </template>
        </el-table-column>-->
        <el-table-column prop="status" label="服务号绑定" width="120" align="center">
          <template #default="scope">
            <div v-if="isBindWxsp(scope.row)" style="display: flex;align-items: center;">
              <!--<el-tag size="mini" type="success">已绑定</el-tag>-->
              <el-button
                type="text"
                size="small"
                         @click="handleShowUnbind(scope.row)"
                style="color:#67C23A;">解除绑定
              </el-button>
            </div>
            <el-button
              v-else
              type="primary"
              plain
              size="small"
              @click="handleShowQrcode(scope.row)"
            >扫码绑定
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="rolerels"
          label="角色">
          <template #default="scope">
            <el-tag
              v-if="scope.row.type === 'SUPER' || scope.row.type === '_SUPER'"
              type="success"
              size="small"
              class="mr-1"
            >{{ adminTypeLabel(scope.row.type) }}
            </el-tag>
            <el-tag
              v-for="r in scope.row.rolerels"
              size="small"
              class="mr-1"
            >{{ r.role.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="290"
          fixed="right"
        >
          <template #default="scope">
            <!--<el-button size="mini" type="text" @click="handleView(scope.row, scope.$index)">查看</el-button>-->
            <el-button
              size="small"
              type="text"
              @click="handleShowMenu(scope.row, scope.$index)"
            >查看菜单</el-button>
            <el-button
              v-if="canMod(scope.row)"
              size="small"
              type="text"
              @click="handleEdit(scope.row, scope.$index)">
              修改
            </el-button>
            <el-button
              size="small"
              type="text"
              @click="handleShowChangePwd(scope.row, scope.$index)"
            >修改密码
            </el-button>
            <el-button
              size="small"
              type="text"
              @click="handleRemoveAdmin(scope.row, scope.$index)"
            >移除管理员
            </el-button>
            <el-button
              size="small"
              type="text"
              @click="handleDelete(scope.row, scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      @size-change="refresh"
      @current-change="refresh"
    />

    <el-dialog
      :title="winName"
      v-model="showCreate"
      top="60px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <AdminCreate
        @close="closeWin"
        :mod-id.sync="modId"
        :show.sync="showCreate"
        :is-view.sync="isView"
      />
    </el-dialog>

    <el-dialog
      title="批量选择管理员"
      v-model="showAppend"
      top="60px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <AdminAppend
        @close="closeWin"
        :show="showAppend"
      />
    </el-dialog>

    <el-dialog
      v-model="qrcodeShow"
      :title="qrcodeWinName"
      :append-to-body="true"
      width="400px"
    >
      <div class="w-full text-center">
        <Qrcode
          :value="qrcodeBindUrl"
          size="200"
          style="margin: 0 auto;"
        />
        <div class="mt-2">{{ qrcodeWinName }}</div>
      </div>
    </el-dialog>

    <el-drawer
      :title="userMenuTitle"
      v-model="userMenuShow"
      direction="rtl"
      size="640px"
    >
      <div class="user-menu-tree-list">
        <perfect-scrollbar
          :settings="{}"
          v-loading="userLoading"
          class="h-full pr-2"
        >
          <h6>已分配-后台管理菜单</h6>
          <el-tree
            ref="selectedtreeRef"
            class="menu-custom-tree tree-empty-image"
            :data="userMenus"
            default-expand-all
            :props="treeSetting"
            :filter-node-method="handleMenuFilter">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
          <h6>已分配-电脑端菜单</h6>
          <el-tree
            ref="selectedtreeT3Ref"
            class="menu-custom-tree tree-empty-image"
            :data="userMenus"
            default-expand-all
            :props="treeSetting"
            :filter-node-method="handleMenuFilterT3">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
          <h6>已分配-手机端菜单</h6>
          <el-tree
            ref="selectedtreeT2Ref"
            class="menu-custom-tree tree-empty-image"
            :data="userMenus"
            default-expand-all
            :props="treeSetting"
            :filter-node-method="handleMenuFilterT2">
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>

          <h6>已分配-接口权限</h6>
          <el-tree
            ref="selectedtreeT9"
            class="menu-custom-tree tree-empty-image"
            :data="userMenus"
            default-expand-all
            :props="treeSetting"
            :filter-node-method="handleMenuFilterT9"
          >
            <template #default="{ node, data }">
              <tree-item-name :data="data"></tree-item-name>
            </template>
          </el-tree>
        </perfect-scrollbar>
      </div>
    </el-drawer>

    <el-dialog
      title="修改用户密码"
      v-model="pwdShow"
      top="60px"
      width="450px"
      :close-on-click-modal="false"
      :append-to-body="true">
      <h3
        v-html="pwdTip || '修改密码'"
        style="margin: 5px 0px 20px;text-align: center;font-size:20px;"
      ></h3>
      <el-form
        :model="pwdForm"
        ref="pwdFormRef"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          label="修改密码"
          prop="pwd1">
          <el-input
            v-model="pwdForm.pwd1"
            type="password"
            autocomplete="off"
            style="width:280px;"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="pwd2">
          <el-input
            v-model="pwdForm.pwd2"
            type="password"
            autocomplete="off"
            style="width:280px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleChangePwd()"
            size="medium"
          >确 定
          </el-button>
          <el-button
            @click="handlePwdClose()"
            size="medium"
          >取 消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.user-menu-tree-list {
  position: absolute;
  top: 50px;
  left: 20px;
  bottom: 10px;
  right: 5px;

  .menu-custom-tree {
    background: #FAFAFA;
    border-radius: 5px;
  }

  h6 {
    font-size: 13px;
    margin: 8px 0px;
    font-weight: bold;
  }
}
</style>
